import { createRouter, createWebHistory } from 'vue-router'
import { isLogin } from '../utils/auth'

const routes = [
    {
        path: '/',
        component: () => import('../layout/Layout.vue'), // 主布局组件
        children: [
            { path: '', redirect: 'recommend' }, // 默认跳推荐页
            { path: 'recommend', component: () => import('../views/RecommendView.vue') },
            { path: 'library', component: () => import('../views/LibraryView.vue') },
            { path: 'singer', component: () => import('../views/SingerView.vue') },
            { path: 'playlist', component: () => import('../views/PlaylistView.vue') },
            {
                path: 'like',
                component: () => import('../views/LikeView.vue'),
                meta: { requiresAuth: true }
            },
            {
                path: 'profile',
                component: () => import('../views/ProfileView.vue'),
                meta: { requiresAuth: true }
            }
        ]
    }
]

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes
})

// 全局路由守卫（拦截需登录页面）
router.beforeEach((to, from, next) => {
    const needLogin = to.matched.some(item => item.meta.requiresAuth)
    if (needLogin && !isLogin()) {
        window.dispatchEvent(new CustomEvent('showLoginModal'))
        next(false)
    } else {
        next()
    }
})

export default router
